
"""
支持model ctp/dwi
执行python3 model_result_get.py -m ctp
或者
python3 model_result_get.py -m dwi
可以获取对应结果
文件保存于/home/biomind/下，ctp数据分析结果.csv，或者dwi数据分析结果.csv
"""
import sys  # noqa
sys.path.append('/home/biomind/.biomind/radiology/Biomind-Server')  # noqa
import os  # noqa
from django.core.wsgi import get_wsgi_application  # noqa
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'biomind.settings')  # noqa
application = get_wsgi_application()  # noqa
import argparse
from decimal import Decimal
from com_models.types import TaskDeleteStatus
from predicts.models import Predicts, Study, Segments
import pandas as pd
parser = argparse.ArgumentParser(description="get ctp/dwi analysis result")
parser.add_argument("--model", '-m', type=str, required=False, default='dwi')
args = parser.parse_args()
model_map = {'ctp': 'brainctp_predictor', 'dwi': 'brainmri_predictor'}


def write_result(model):
    model_objs = Predicts.objects.filter(
        predictor=model_map[model],
        task_id__is_active=TaskDeleteStatus.effective).order_by('study_uid')
    # .values('study_uid').annotate(study_count=Count('study_uid')).filter()
    res = []
    for obj in model_objs:
        temp = dict()
        study_infos = Study.objects.filter(internalid=obj.task_id.internalid)
        if not study_infos.exists():
            continue
        study_info = study_infos[0]
        temp['accession_number'] = study_info.accession_number
        temp['patient_name'] = study_info.patient_name
        temp['patient_id'] = study_info.patient_id
        temp['study_uid'] = study_info.study_instance_uid
        temp['patient_birth_date'] = study_info.patient_birth_date
        temp['patient_sex'] = study_info.patient_sex
        temp['patient_age'] = study_info.patient_age
        temp['study_datetime'] = study_info.study_datetime
        if model == 'ctp':
            prediction = obj.prediction
            temp['分析结果'] = {v['cn']: v['value'] for v in prediction.get('classification', {}).values()}
            volumes = prediction.get('perfusion_volumes', {})
            temp['cbf 参数'] = volumes.get('volume_cbf', {})
            temp['cbv 参数'] = volumes.get('volume_cbv', {})
            volume_tmax = volumes.get('volume_tmax', {})
            volume_tmax['hir'] = round(prediction.get('perfusion_parameters', {}).get('hir', 0), 2)
            volume_tmax.pop('4', '')

            temp['tmax 参数'] = volume_tmax
            res.append(temp)
        elif model == 'dwi':
            volumes = Segments.objects.filter(predict_id=obj, dkey='gengsi').values_list('extensions__volume')
            for i, volume in enumerate(volumes, start=1):
                if volume is not None:
                    temp['梗死体积' + str(i)] = round(volume[0], 2)
            res.append(temp)

    if res:
        ds = pd.DataFrame(res)
        ds.to_csv(f'/home/biomind/{model}数据分析结果.csv')


if __name__ == '__main__':
    if args.model not in model_map:
        raise Exception('model is not defined')
    write_result(args.model)
